const express = require("express");
const app = express();
const cors = require("cors");
const expressJWT = require("express-jwt");
const joi = require("joi");

// 配置 CORS 跨域
app.use(cors());

require('dotenv').config();


// 配置解析表单数据的中间件
app.use(express.urlencoded({ extended: false }));

// 解析 JSON 请求体
app.use(express.json());

// 托管静态资源文件
app.use('/uploads', express.static('./uploads'));

// 响应数据的中间件
app.use(function (req, res, next) {
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});

// 导入配置文件
const config = require("./config");

// 解析 token 的中间件
app.use(
  expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] })
);

// 导入并使用路由模块
const userRouter = require("./router/user");
app.use("/api", userRouter);

const userinfoRouter = require('./router/userinfo');
app.use('/my', userinfoRouter);

const websiteCategoryRouter = require('./router/websitecategory');
app.use('/my/website', websiteCategoryRouter);

const bannerRouter = require('./router/banner');
app.use('/my/banner', bannerRouter);

const recommendRouter = require('./router/recommend');
app.use('/my/recommend', recommendRouter);

const websiteRouter = require('./router/website');
app.use('/my/websiteall', websiteRouter);

const userLayoutRouter = require('./router/userlayout');
app.use('/my/userlayout', userLayoutRouter);

// 错误处理中间件
app.use(function (err, req, res, next) {
  if (err instanceof joi.ValidationError) return res.cc(err);
  if (err.name === "UnauthorizedError") return res.cc("身份认证失败！");
  res.cc(err);
});

// 启动服务器
app.listen(3000, function () {
  console.log("api server running at http://127.0.0.1:3000");
});
